/*
 * Copyright 2009 eBusinessInformation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.excilys.ymca.activity;

import java.io.File;

import roboguice.activity.GuiceActivity;
import roboguice.inject.ContextScoped;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

import com.excilys.ymca.R;
import com.excilys.ymca.task.UpdateApplicationTask;
import com.google.inject.Inject;
import com.google.inject.Provider;

/**
 * Activité de mise à jour de l'application.
 * 
 * @author Pierre-Yves Ricau ( py.ricau+ymca @ gmail.com )
 */
@ContextScoped
public class UpdateApplicationActivity extends GuiceActivity implements ApplicationUpdateListener {

	/**
	 * On utilise un Provider pour les ASyncTask, car elles ne peuvent être
	 * utilisées qu'une seule fois. Ce n'est pas absolument nécessaire ici, mais
	 * c'est une bonne pratique à adopter.
	 * 
	 * Guice va automatiquement créer le Provider nécessaire et l'injecter.
	 */
	@Inject
	private Provider<UpdateApplicationTask>	updateApplicationTaskProvider;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

		setContentView(R.layout.update_application);

		setProgressBarIndeterminateVisibility(true);

		/**
		 * On récupère le code de version situé dans le fichier
		 * AndroidManifest.xml (tag manifest, attribut android:versionCode)
		 */
		PackageInfo packageInfo;
		try {
			packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			throw new IllegalStateException("Should not happen", e);
		}

		updateApplicationTaskProvider.get().execute(packageInfo.versionCode);

	}

	public void onApplicationUpToDate() {
		Toast.makeText(this, R.string.updating_up_to_date, Toast.LENGTH_SHORT).show();
		startActivity(new Intent(this, ContactListActivity.class));
	}

	public void onUpdateFailed(Exception e) {

		String message = String.format(getString(R.string.updating_failed_message), e.getMessage());

		/*
		 * Notez l'utilisation de commentaires vides (//) pour rendre lisible
		 * les chaining methods. En l'absence de //, Eclipse reformate le code
		 * de manière peu lisible.
		 */
		new AlertDialog.Builder(this)//
				.setTitle(R.string.updating_failed_title) //
				.setCancelable(false) //
				.setMessage(message) //
				.setPositiveButton(R.string.updating_failed_continue, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						startActivity(new Intent(UpdateApplicationActivity.this, ContactListActivity.class));
					}
				}) //
				.setNegativeButton(R.string.updating_failed_exit, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				})//
				.create()//
				.show();
	}

	@Override
	public void onUpdateDownloaded(File file) {
		Intent i = new Intent();
		i.setAction(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		startActivity(i);
	}

}
